public class BinarySearch {
    static class TreeNode{
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    public TreeNode root;

    /*
    * 二叉搜索树
    * 时间复杂度：O(logN)
    *   最坏情况：O(N)(单分支的树)
    * */
    public boolean search(int val){
        if(root == null) return false;
        TreeNode cur = root;
        while(cur != null){
            if(cur.val < val){
                cur = cur.right;
            }else if(cur.val > val){
                cur = cur.left;
            }else{
                return true;
            }
        }
        return false;
    }

    //插入都是插入到二叉树的叶子结点
    public void insert(int val){
        TreeNode node = new TreeNode(val);
        if(root == null) {
            root = node;
            return ;
        }
        TreeNode cur = root;
        TreeNode parent = null;
        while(cur != null){
            if(cur.val < val){
                parent = cur;
                cur = cur.right;
            }else if(cur.val > val){
                parent = cur;
                cur = cur.left;
            }else{
                System.out.println("已有该数");
                return ;
            }
        }
        if(parent.val < val){
            parent.right = node;
        }
        if(parent.val > val){
            parent.left = node;
        }
    }

    //二叉搜索树的删除
    public void remove(int val){
        TreeNode cur = root;
        TreeNode parent = null;
        while(cur != null){
            if(cur.val < val){
                parent = cur;
                cur = cur.right;
            }else if(cur.val > val){
                parent = cur;
                cur = cur.left;
            }else{
                removeNode(parent,cur);
                return;
            }
        }

    }

    private void removeNode(TreeNode parent, TreeNode cur) {
        if(cur.left == null){
            if(cur == root){
                root = cur.right;
            }else if(cur == parent.left){
                parent.left = cur.right;
            }else{
                parent.right = cur.right;
            }
        } else if (cur.right == null) {
            if(cur == root){
                root = cur.left;
            }else if(cur == parent.left){
                parent.left = cur.left;
            }else{
                parent.right = cur.left;
            }
        }else{
            //两边都不为空，则使用替换法
            //要么找到 cur 左子树的最大值
            //要么找到 cur 右子树的最小值
            TreeNode target = cur.right;
            TreeNode targetParent = cur;
            while(target.left != null){
                targetParent = target;
                target = target.left;
            }
            cur.val = target.val;
            if(targetParent.left == target){
                targetParent.left = target.right;
            }else{
                targetParent.right = target.right;
            }
        }
    }
}
